//
//  AiRoleManager.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/1.
//

import Foundation
import LeanCloud

var aiRoleManager = AiRoleManager()

class AiRoleManager : BaseViewModel {
    
    @Published var listSystemRole:[AiRoleBean]? = nil
    
    func getSystemAiRoleList() async throws -> [AiRoleBean] {
        if listSystemRole != nil {
//            showLog("系统角色已经加载过了")
            return listSystemRole!
        }
        let list = try await retry(maxRetries: 3, retryDelayMillis: 100) {
            let serveRequest = configManager.getConfig().serverRequest ?? ServerRequestBean()
            if (serveRequest.isCloudAiRole()) {
                showLog("AiRole", "请求leanCloud")
                let query = LCQuery(className: "AiRole")
                query.whereKey("isSystem", .equalTo(true))
                query.whereKey("sort", .ascending) //升序
                return try await LeancloudManager.instance.getList(query: query, modeType: AiRoleBean.self)
            } else {
                let url = configManager.getConfig().serverRequest?.aiSystemRoleList ?? ""
                showLog("AiRole", "请求json文件")
                var list = try await CommonNetManager.shared.get(url: url, modeType: [AiRoleBean].self)
                list = list.sorted { $0.sort < $1.sort }
                return list
            }
          
        }
        showLog("AiRole", "系统角色：\(list.count)")
        listSystemRole = list
        return list
    }
}
